package com.ttg.web.service.Impl;


import com.github.pagehelper.PageHelper;
import com.ttg.common.entities.RattingTask;
import com.ttg.common.enums.TagDataSourceEnum;
import com.ttg.common.enums.TaskEnum;

import com.ttg.common.enums.VersionStatusEnum;
import com.ttg.model.pojo.PeopleHistory;
import com.ttg.model.pojo.PeopleInfo;
import com.ttg.model.pojo.VipBindPeople;
import com.ttg.model.pojo.VipBindTag;
import com.ttg.web.dao.PeopleHistoryDao;
import com.ttg.web.dao.PeopleInfoDao;
import com.ttg.web.dao.VipBindPeopleDao;
import com.ttg.web.dao.VipBindTagDao;
import com.ttg.web.service.ManagePeopleInfoService;
import com.ttg.web.utils.NextUpdateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ManagePeopleInfoServiceImpl implements ManagePeopleInfoService {

    @Autowired
    private PeopleInfoDao peopleInfoDao;


    @Autowired
    private VipBindTagDao vipBindTagDao;

    @Autowired
    private VipBindPeopleDao vipBindPeopleDao;

    @Autowired
    private PeopleHistoryDao peopleHistoryDao;

    //@RattingTask(taskEnum = TaskEnum.VIP_PEOPLE_BIND)
    @Override
    public void vipPeopleBind() {
        //获取所有用户人群
        List<PeopleInfo> list = peopleInfoDao.getAllByTypeAndStatus(TagDataSourceEnum.USER);
        for (PeopleInfo peopleInfo : list) {
            //检查当前时间>=下次更新时间，满足才本次更新
            LocalDateTime updateTime = peopleInfo.getPepNextUpdateTime();
            LocalDateTime now = LocalDateTime.now();
            if (!(now.compareTo(updateTime) >= 0)) {
                continue;
            }
            //根据更新频率计算下次更新时间，保存到人群表
            LocalDateTime nextUpdateTime = NextUpdateTimeUtil.firstUpdateTime(peopleInfo);
            asyncUpdateVipPeople(peopleInfo, nextUpdateTime,updateTime);

        }
    }

    @RattingTask(taskEnum = TaskEnum.MCT_PEOPLE_BIND)
    @Override
    public void mctPeopleBind() {
        List<PeopleInfo> list = peopleInfoDao.getAllByTypeAndStatus(TagDataSourceEnum.MERCH);
        for (PeopleInfo peopleInfo : list) {
            //检查当前时间>=下次更新时间，满足才本次更新
            LocalDateTime updateTime = peopleInfo.getPepNextUpdateTime();
            LocalDateTime now = LocalDateTime.now();
            if (!(now.compareTo(updateTime) >= 0)) {
                continue;
            }
            peopleInfo.setVersionStatus(VersionStatusEnum.PROCESSING.getCode());
            //根据更新频率计算下次更新时间，保存到人群表
            LocalDateTime nextUpdateTime = NextUpdateTimeUtil.firstUpdateTime(peopleInfo);
            asyncUpdateVipPeople(peopleInfo, nextUpdateTime,updateTime);

        }
    }

    public void asyncUpdateVipPeople(PeopleInfo peopleInfo, LocalDateTime nextUpdateTime, LocalDateTime lastupdateTime) {
        try {
            //获取包含和排除的标签ID
            List<String> containsTagIds = Arrays.asList(peopleInfo.getContainsTagIds().split(","));
            List<String> excludeTagIds = Arrays.asList(peopleInfo.getExcludeTagIds().split(","));
            //查询tbl_app_coupon_vip_bind_tag表中人群信息
            List<VipBindTag> vipBindTagList = vipBindTagDao.selectBytags(containsTagIds, excludeTagIds);
            //删除原人群会员绑定关系
            vipBindPeopleDao.deleteBytPepId(peopleInfo.getId());
            // 执行人群计算并保存结果
            List<VipBindPeople> vipBindPeopleList = new ArrayList<>();
            for (VipBindTag vipBindTag : vipBindTagList) {
                VipBindPeople vipBindPeople = new VipBindPeople();
                vipBindPeople.setPepId(peopleInfo.getId());
                vipBindPeople.setVipId(vipBindTag.getVipId());
                vipBindPeople.setAddTime(LocalDateTime.now());
                if (!StringUtils.isEmpty(vipBindTag.getMctNo())) {
                    vipBindPeople.setMctNo(vipBindPeople.getMctNo());
                }
                vipBindPeopleList.add(vipBindPeople);
            }
            //保存人群会员绑定
            int num = vipBindPeopleDao.addVipBindPeople(vipBindPeopleList);
            //更新人群表
            PeopleInfo people = new PeopleInfo();
            people.setId(peopleInfo.getId());
            if (nextUpdateTime != null) {
                people.setPepNextUpdateTime(nextUpdateTime);
            }
            people.setPepNum(num);
            people.setVersionStatus(VersionStatusEnum.SUCCESS.getCode());
            peopleInfoDao.updateById(people);
            //更新人群执行表
            PeopleHistory peopleHistory = new PeopleHistory();
            peopleHistory.setPepId(peopleInfo.getId());
            peopleHistory.setHisRunTime(lastupdateTime);
            peopleHistory.setHisRealRunTime(LocalDateTime.now());
            peopleHistory.setHisDescription("更新人群成功");
            peopleHistory.setHisStatus(VersionStatusEnum.SUCCESS.getCode());
            peopleHistoryDao.save(peopleHistory);
        } catch (Exception e) {
            //更新失败
            PeopleInfo people = new PeopleInfo();
            people.setId(peopleInfo.getId());
            if (nextUpdateTime != null) {
                people.setPepNextUpdateTime(nextUpdateTime);
            }
            people.setPepNum(null);
            people.setVersionStatus(VersionStatusEnum.FAIL.getCode());
            peopleInfoDao.updateById(people);
            PeopleHistory peopleHistory = new PeopleHistory();
            peopleHistory.setPepId(peopleInfo.getId());
            peopleHistory.setHisRunTime(lastupdateTime);
            peopleHistory.setHisRealRunTime(LocalDateTime.now());
            peopleHistory.setHisDescription("更新人群失败,失败原因:" + e.getMessage());
            peopleHistory.setHisStatus(VersionStatusEnum.FAIL.getCode());
            peopleHistoryDao.save(peopleHistory);
        }

    }

}
